import { type Options } from './type';
import Resize from './resize';
import { onMounted, watch } from 'vue';
import Sortable from 'sortablejs';

export default class extends Resize {
  constructor(options: Options) {
    super(options);
    onMounted(() => {

      let SortableTr: any;
      watch(() => this.props.showRowDrag, () => {
        if(this.props.showRowDrag){
          SortableTr = new Sortable(this.table.value?.querySelector('tbody'), {
            handle: '.row-index>.sort-handel',
            filter: '.disable-edit-row',
            animation: 150,
            onEnd: ({ newIndex, oldIndex }) => {
              if(this.props.openUndo && this.emptyHistoryRecord()) this.addHistoryRecord();
              
              const n = newIndex;
              const o = oldIndex;
  
              const target = this.dataSource.value[o];
              this.dataSource.value.splice(o, 1);
              this.dataSource.value.splice(n, 0, target);
  
              this.selectedState.endY = this.selectedState.startY = n;

              if(this.props.openUndo) this.addHistoryRecord();
            },
          });
        } else {
          SortableTr?.destroy?.();
        }
      }, {
        immediate: true
      })

      let SortableTh: any;
      watch(() => this.props.showColDrag, () => {
        if (this.props.showColDrag) {
          SortableTh = new Sortable(this.table.value?.querySelector('thead>tr'), {
            animation: 150,
            draggable: "th:not(.row-index):not(.row-check)",
            filter: '.row-index, .row-check',
            onEnd: ({ newIndex, oldIndex }) => {
              if(this.props.openUndo && this.emptyHistoryRecord()) this.addHistoryRecord();

              let offset = 0;
  
              if (this.props.showRowIndex) offset += 1;
              if (this.props.rowSelection) offset += 1;
  
              const n = newIndex - offset;
              const o = oldIndex - offset;
  
              const target = this.columns.value[o];
              this.columns.value.splice(o, 1);
              this.columns.value.splice(n, 0, target);

              this.selectedState.startX = this.selectedState.endX = n

              if(this.props.openUndo) this.addHistoryRecord();
            },
          });
        } else {
          SortableTh?.destroy?.();
        }
      }, {
        immediate: true
      })
    });
  }

  dragRow(rowindex: number) {
    this.selectedState.endY = this.selectedState.startY = rowindex;
    this.selectedState.startX = this.selectedState.endX = -1;
  }
}
